import 'package:BeeApp/MainPage/MainModelPage.dart';
import 'package:BeeApp/MainPage/MainSetModel.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:flutter/material.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

class KefuPage extends StatefulWidget {
  KefuPage({Key key}) : super(key: key);

  @override
  _KefuPageState createState() => _KefuPageState();
}

class _KefuPageState extends State<KefuPage> {
  final beizhuText = TextEditingController();
  List<Asset> images = List<Asset>();
  List<String> imageUrl = [];
  MainSetModel keFuModel;

  @override
  void initState() {
    super.initState();
    uploadData();
  }

  void uploadData() {
    DioUtils.noTokenPostHttp(
      context,
      "Usercommon/app_config",
      onSuccess: (t) {
        print(t);
        MainModel model = MainModel.fromJson(t);
        if (model.code == 1 && model.data != null) {
          if (mounted) {
            setState(() {
              keFuModel = MainSetModel.fromJson(t);
            });
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: getAppBar(context, "客服中心"),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: ListView(
          children: <Widget>[
            Container(color: Color(0xFFF5F5F5), height: 10),
            mobileView(),
            Container(color: Color(0xFFF5F5F5), height: 10),
            weixinView(),
            Container(color: Color(0xFFF5F5F5), height: 10),
            beizhutextView(),
            shopImageView(),
            SizedBox(height: setHeight(20)),
            sendBtnView()
          ],
        ),
      ),
    );
  }

  Widget mobileView() {
    return InkWell(
      child: Container(
        height: 50,
        color: Colors.white,
        padding: EdgeInsets.only(left: 20, right: 20),
        child: Row(
          children: [
            Image.asset(
              "images/KFMobileImage.png",
              width: setWidth(60),
            ),
            SizedBox(width: 10),
            Text(
              "客服电话",
              style: TextStyle(fontSize: setFontSize(30)),
            ),
            SizedBox(width: 5),
            Expanded(
                child: Text(keFuModel == null ? "" : keFuModel.data.csMobile)),
          ],
        ),
      ),
      onTap: () {
        print("object");
        launch("tel://${keFuModel.data.csMobile}");
      },
    );
  }

  // void _pressed() async {
  //   // Android
  //   print("open weixin");
  //   const url = 'vnd.weixin://';
  //   if (await canLaunch(url)) {
  //     await launch(url);
  //   } else {
  //     //  Ios
  //     const url = 'weixin://';
  //     if (await canLaunch(url)) {
  //       await launch(url);
  //     } else {
  //       throw 'Could not launch $url';
  //     }
  //   }
  // }

  Widget weixinView() {
    return InkWell(
      child: Container(
        height: 50,
        color: Colors.white,
        padding: EdgeInsets.only(left: 20, right: 20),
        child: Row(
          children: [
            Image.asset(
              "images/KFeMileImage.png",
              width: setWidth(60),
            ),
            SizedBox(width: 10),
            Text(
              "电子邮箱",
              style: TextStyle(fontSize: setFontSize(30)),
            ),
            SizedBox(width: 5),
            Expanded(
                child: Text(keFuModel == null ? "" : keFuModel.data.email)),
          ],
        ),
      ),
      onTap: () {
        print("object");
        // _pressed();
      },
    );
  }

  Widget beizhutextView() {
    return Container(
      padding: EdgeInsets.all(setWidth(30)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "投诉建议",
            style: TextStyle(
              color: Color(0xFF333333),
              fontSize: setFontSize(30),
            ),
          ),
          SizedBox(height: 8),
          Container(
            padding: EdgeInsets.only(
              left: setWidth(30),
              right: setWidth(30),
            ),
            decoration: BoxDecoration(
              // color: Color(0xFFFF8629),
              // borderRadius: BorderRadius.all(Radius.circular(10)),
              border: Border.all(color: Color(0xFFCBCBCB), width: 1), //边框
            ),
            child: TextField(
              maxLines: 5,
              controller: beizhuText,
              textAlign: TextAlign.start,
              cursorColor: Colors.grey[400], //设置光标
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: "请输入您想要投诉的订单信息...",
                  hintStyle: TextStyle(
                      fontSize: setFontSize(30), color: Color(0xFFAEAEAE))),
              style: TextStyle(fontSize: setFontSize(30), color: Colors.black),
            ),
          ),
        ],
      ),
    );
  }

  GridView shopImageView() {
    return GridView.builder(
      shrinkWrap: true,
      //解决无限高度问题
      physics: NeverScrollableScrollPhysics(),
      //禁用滑动事件
      padding: const EdgeInsets.all(10.0),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 10.0,
        crossAxisSpacing: 10.0,
        // childAspectRatio: 3 / 5,
      ),
      itemCount: images.length + 1,
      itemBuilder: (BuildContext context, int index) {
        return showview(index);
      },
    );
  }

  Widget showimage(int index) {
    if (index == images.length) {
      return Container(
        child: Image.asset("images/MainAddImage.png"),
      );
    } else {
      Asset asset = images[index];
      return AssetThumb(
        asset: asset,
        width: 300,
        height: 300,
      );
    }
  }

  // 展示相册图片
  Widget showview(int index) {
    return Container(
      // color: Colors.red,
      child: Stack(
        children: [
          InkWell(
            child: Container(
              // color: Colors.orange,
              height: 120,
              // padding: EdgeInsets.only(top: 10, right: 10),
              child: showimage(index),
            ),
            onTap: () async {
              print("aaaa");
              if (index == images.length) {
                if (await Permission.camera.request().isGranted &&
                    await Permission.photos.request().isGranted) {
                  loadAssets();
                  print('权限申请通过');
                } else {
                  showToast('请前往设置，打开相机权限');
                }
              }
            },
          ),
          Positioned(
            top: index == images.length ? -100 : 0,
            right: index == images.length ? -100 : 0,
            child: InkWell(
              child: Container(
                decoration: BoxDecoration(
                  color: Color(0xFF1C80F8),
                  borderRadius: BorderRadius.all(Radius.circular(15)),
                ),
                child: Image.asset("images/KFDismissImage.png",
                    width: setWidth(40)),
              ),
              onTap: () {
                print("$index");
                setState(() {
                  images.removeAt(index);
                });
              },
            ),
          ),
        ],
      ),
      // ),
    );
  }

  // 获取相册图片
  Future<void> loadAssets() async {
    List<Asset> resultList = List<Asset>();
    String error = 'No Error Dectected';

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 9,
        enableCamera: true,
        selectedAssets: images,
        materialOptions: MaterialOptions(
          startInAllView: true,
          allViewTitle: "所有照片",
          actionBarColor: "#abcdef",
          textOnNothingSelected: "请选择图片",
          selectionLimitReachedText: "最多选择9张图片",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
      print("aaaaa" + error);
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    setState(() {
      if (resultList.length > 0) {
        images = resultList;
      }
    });
  }

  Widget sendBtnView() {
    return Container(
        alignment: Alignment.center,
        child: InkWell(
          child: Container(
            height: setHeight(88),
            width: screenWidth - setWidth(60),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Color(0xFFFF8629),
              borderRadius: BorderRadius.all(Radius.circular(10)),
              border: Border.all(color: Color(0xFF333333), width: 2), //边框
            ),
            child: Text(
              "确定",
              style: TextStyle(
                color: Color(0xFF222222),
                fontSize: setFontSize(32),
              ),
            ),
          ),
          onTap: () {
            print("发表评价");
            // if (beizhuText.text.length == 0) {
            //   showToast("请输入反馈意见");
            //   return;
            // }
            if (images.length == 0) {
              showToast("请提供图片依据");
              return;
            }
            uploadImage();
          },
        ));
  }

  void uploadImage() {
    showLoading(context);
    DioUtils.postImageHttp(
      context,
      "common/uploads",
      images: images,
      onSuccess: (t) {
        print(t);
        if (t["code"].toString() == "1") {
          List arr = List.of(t["data"]["url"]);
          getStringWithList(arr);
          for (var i = 0; i < arr.length; i++) {
            var str = arr[i];
            imageUrl.add(str.toString());
          }
          print(imageUrl);
          uploadNews(getStringWithList(arr));
        } else {
          dismissLoading(context);
        }
      },
      onError: (error) {
        dismissLoading(context);
        print(error);
      },
    );
  }

  void uploadNews(String imageStr) {
    DioUtils.postHttp(
      context,
      "Usercommon/save_complaint",
      parameters: {
        "token": getData("token"),
        "content": beizhuText.text.length == 0 ? "" : beizhuText.text,
        "images": imageStr
      },
      onSuccess: (t) {
        print(t);
        showToast(t["msg"]);
        dismissLoading(context);
        if (t["code"].toString() == "1") {
          if (mounted) {
            setState(() {
              images?.clear();
              beizhuText.text = "";
            });
          }
        }
      },
      onError: (error) {
        dismissLoading(context);
        print(error);
      },
    );
  }
}
